package com.study.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

/**
 * @author mjy(服务端netty启动)
 * @date 2021/12/06
 * @description
 */
@Component
public class NettyServer {


    /**
     * 创建两个线程组bossGroup和workGroup
     * boss只是处理连接请求，真正的和客户端业务处理，会交给workGroup完成
     * 两个都是无限循环
     */

    private EventLoopGroup bossGroup = new NioEventLoopGroup(1);

    private EventLoopGroup workerGroup = new NioEventLoopGroup(4);

    private void start(InetSocketAddress address) {
        try {
            //创建服务端的启动对象，配置参数
            ServerBootstrap bootstrap = new ServerBootstrap();
            //设置两个线程组
            bootstrap.group(bossGroup, workerGroup);
            //使用NioServerSocketChannel作为服务器的通道实现
            bootstrap.channel(NioServerSocketChannel.class);
            //设置socket连接地址
            bootstrap.localAddress(address);
            //给工作组的EventLoop对应的管道设置处理器
            bootstrap.childHandler(new ServerChannelInitializer());
            //option主要作用于boss线程,optionChildOption主要用来处于工作线程
            bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
            //探测机制ChannelOption.SO_KEEPALIVE
            bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
            //绑定端口，开始接受进来的连接
            bootstrap.bind(address).sync();
            ChannelFuture future = bootstrap.bind(address);
            if (future.isSuccess()) {
                System.out.println("启动 netty 成功");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }


    }


}
